<route type="page" lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '用户信息'
  }
}
</route>

<template>
  <view>
    <wd-form :model="formData" ref="formRef" border>
      <view v-for="(item, index) in formData.contactPersonInfoDtoList" :key="index">
        <view class="flex flex-justify-between m-3 box-border flex-items-center">
          <text class="text-lg font-size-3 font-800">联系人{{ index + 1 }}</text>
          <view>
            <text class="font-size-3 c-#347cd0 mr-3" @click="addList">添加</text>
            <text class="font-size-3 c-red" @click="deleteList(index)">删除</text>
          </view>
        </view>
        <wd-card>
          <wd-input label="用户昵称" prop="username" v-model="item.name" placeholder="请输入用户名" />
          <wd-input prop="mobile" label="手机号" placeholder="请输入手机号" v-model="item.mobile" />
          <wd-input label="备注" prop="relation" v-model="item.relation" placeholder="请输入如第一联系人等" />
        </wd-card>
      </view>
      <view class="my-3 mx-2">
        <wd-button type="primary" :block="true" @click="submit">提交</wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { getUserApi, setUserContactApi } from '@/api/loginApi'

const addList = () => {
  formData.value.contactPersonInfoDtoList.push({ name: '', mobile: '', relation: '' })
}
const deleteList = (index: number) => {
  formData.value.contactPersonInfoDtoList.splice(index, 1)
}

const formData = ref({ contactPersonInfoDtoList: [] })
const formRef = ref()

const submit = async () => {
  let validate = await formRef.value.validate()

  if (!validate.valid) return

  await setUserContactApi(formData.value)
  uni.showToast({ title: '保存成功', icon: 'success' })
  setTimeout(() => {
    uni.navigateBack()
  }, 1000)
}
onMounted(async () => {
  const res: any = await getUserApi()
  if (!res.data.contactPersonInfoDtoList || !res.data.contactPersonInfoDtoList.length) {
    res.data.contactPersonInfoDtoList = [{ name: '', mobile: '', relation: '' }]
  }
  formData.value = {
    contactPersonInfoDtoList: res.data.contactPersonInfoDtoList
  }
})
</script>

<style lang="scss" scoped></style>
